package chances.epg.ui.taglib.filter;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.io.Closeables;
import com.google.common.io.Files;

public class ResourceFilter implements Filter {

	private ServletContext servletContext;
	String resPath = "/chances/epg/ui/taglib/js/";
	private Set<String> jsNmaes = new HashSet<String>();

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
	
		if (!filter((HttpServletRequest) request,
				(HttpServletResponse) response)) {
			chain.doFilter(request, response);
		}
	}

	public boolean filter(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String path = request.getServletPath();
		String fileName = Files.getNameWithoutExtension(path);
		fileName = fileName + "."+Files.getFileExtension(path);
		if (jsNmaes.contains(fileName)) {
			InputStream in = this.getClass().getResourceAsStream(resPath + fileName);
			response.setContentType(this.servletContext.getMimeType(fileName));
			response.setHeader("Cache-Control","public");
			response.setDateHeader("Expires", System.currentTimeMillis()+3000);
			try {
				String text = CharStreams.toString(new InputStreamReader(in,
						Charsets.UTF_8));
				response.getWriter().write(text);
			} finally {
				Closeables.close(in, false);
			}
			return true;
		} else {
			return false;
		}
	}

	public void init(FilterConfig config) throws ServletException {
		servletContext = config.getServletContext();
		String name = config.getInitParameter("names");
		String[] names = name.split(",");
		for (int i = 0; i < names.length; i++) {
			jsNmaes.add(names[i].trim());
		}
		
		 
	}

	public void destroy() {
		jsNmaes.clear();
	}
}
